const router = require('koa-router')()
const mongoose = require('mongoose')
const Response = require('../model/Response')
const moment = require('moment')
const uuid = require('uuid')

// 病人的数据库模型
var PatientSchema = new mongoose.Schema({
  name:String,
  age:String,
  genere:String,
  id: String,
  _id: String,
  blood_sugar: String,
  blood_pressure: String,
  generateDate: Date
});

var Patient = mongoose.model('Patient',PatientSchema);

router.get('/patient/list', async (ctx, next) => {
  let { startDate, endDate } = ctx.query
  console.log(startDate, endDate)
	const data = await Patient.find({generateDate : {$gte : startDate, $lte : endDate}})
  console.log('data', data)
	ctx.response.body = new Response(0, '查询成功', data)
})

router.post('/patient/add', async(ctx, next) => {
  const params = ctx.request.body
  console.log(params)
  const data = await Patient.find({id: params.id})
  if (data.length > 0) {
    ctx.body = {
      status: 1,
      msg: '添加失败，身份证号已存在!',
      data: ''
    }
    return;
  }
  // 新增数据
  var patient = {
    ...params,
    _id: uuid.v1(),
    updateDate: new Date(),
    generateDate: moment().format('yyyy-MM-DD')
  }
  var newPatient = new Patient(patient);
  let result = {}
  try{
    await newPatient.save();
    result = new Response(0, '添加成功', [])
  }catch(e) {
    result = new Response(1, '添加失败', data.msg)
  }
  ctx.body = result
})

router.post('/patient/edit', async(ctx, next) => {
  const params = ctx.request.body
  let result = {}
  console.log(params)
  try {
    const data = await Patient.find({_id: params._id})
    if (data.length === 0) {
      ctx.body = new Response(1, '修改失败，该人员信息不存在!', [])
      return;
    }
    // 修改数据
    var patient = {
      ...params,
      updateDate: new Date()
    }
    // var newPatient = new Patient(patient);
    // await newPatient.updateOne({_id: patient._id}, patient);
    await Patient.updateOne({_id: patient._id}, patient);
    result = new Response(0, '修改成功', [])
  } catch(e) {
    console.log(e)
    result = new Response(1, '修改失败', e.messages)
  }
  ctx.body = result
})

router.get('/patient/delete', async(ctx, next) => {
  const { _id } = ctx.query;
  let result = {}
  try {
    await Patient.deleteOne({_id})
    result = new Response(0, '删除成功', []);
  } catch(e) {
    console.log(e)
    result = new Response(1, '删除失败', e.messages);
  }
  ctx.body = result
})

// export default router
module.exports = router